package com.xiaotu.storage;

import java.util.Date;

import org.springframework.stereotype.Component;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.TVRecordModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.DataRedisKeyUtils;
import com.xiaotu.common.util.GsonUtils;
import com.xiaotu.storage.converter.AConverter;
import com.xiaotu.storage.converter.ConverterFactory;
import com.xiaotu.storage.model.CacheDataModel;

import net.sf.json.JSONObject;

/**
 * @类名 TVNetPlayStorageProcessor
 * @日期 2017年3月2日
 * @作者 高海军
 * @功能 播放量天数据转储
 */
@Component("TVNetPlayStorageProcessor")
public class TVNetPlayStorageProcessor extends TVRecordStorageProcessor
{
	@Override
	public String process(JSONObject target, CacheDataModel cacheData,
			Date date)
	{
		JSONObject currTgt = this.getOneTarget(target, true);// 计算当前累计播放量，数据结构有问题则抛异常
		
		TVRecordModel record = GsonUtils.fromJson(currTgt.toString(),
				TVRecordModel.class);
		JSONObject lastTarget = this.getLastTarget(
				Constants.DataRedisKey.TV_NetPlay_YYYYMMDD, date,
				DataRedisKeyUtils.getTVRecordKey(record));// 获取前一天的对象
		JSONObject lastTgt = this.getOneTarget(lastTarget, false);// 计算前一天对象的累计播放量，若数据结构有问题则为空
		
		if (!this.setDataDay(currTgt, lastTgt, "playCount", "playCountDay",
				false, true))
			return null;
		
		this.validateAllNotEmpty(currTgt, "resourceSiteId", "tvId", "tvName");
		this.validateAllNotEmpty(currTgt, "playCount", "playCountDay");
		if (currTgt.getLong("playCountDay") < 0)
			throw new SpiderException(
					SpiderExceptionCode.DataInvalideException);
		
		return this.list2CSVLine(ConverterFactory.convert(currTgt,
				new String[] { "resourceSiteId", "tvId", "tvName", "playCount",
						"playCountDay", "timestamp" },
				new String[] { AConverter.STRING_CONVERT,
						AConverter.STRING_CONVERT, AConverter.STRING_CONVERT,
						AConverter.INTEGER_CONVERT, AConverter.INTEGER_CONVERT,
						AConverter.TIMESTAMP_CONVERT },
				new boolean[] { true, true, true, true, true,true }));
	}
	
	@Override
	public String getDataType()
	{
		return Constants.PageDataType.TV_NETPLAY_DAY;
	}
}
